import { Effect, Reducer, Subscription } from 'umi';
import request from 'umi-request';

const getRatedList = () => {
  return request
    .get('http://www.pudge.wang:3080/api/rated/list')
    .then((res) => {
      return res;
    });
};

export interface ItemType {
  _id: string;
  title: string;
  [propname: string]: any;
}

export interface IndexModelState {
  list: ItemType[];
}

export interface IndexModelType {
  // 如果有一个字符串，而且这个字符串是不会变的，那么我们可以直接将变量类型写成这个字符串
  namespace: 'todolist';
  state: IndexModelState;
  effects: {
    asyncGetData: Effect;
  };
  reducers: {
    getData: Reducer;
    addData: Reducer;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  // 模块名称
  namespace: 'todolist',

  // 仓库数据
  state: {
    list: [],
  },

  // 写异步函数的, 类似于vuex的actions
  effects: {
    *asyncGetData({ payload }, { call, put }): any {
      // 请求猫眼数据
      const res = yield call(getRatedList);
      yield put({
        type: 'getData',
        result: res.result,
      });
    },
  },

  // 同步函数，类似于vuex的mutations
  reducers: {
    getData(state, action) {
      return {
        ...state,
        list: action.result,
      };
    },
    addData(state, action) {
      return {
        ...state,
        list: [...state.list, { _id: '123frtgrth45g45', title: action.title }],
      };
    },
  },

  // 可以用于做url监听之类的
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        // console.log(pathname);

        if (pathname === '/todolist') {
          // dispatch({
          //   type: 'query',
          // });
          dispatch({
            type: 'asyncGetData',
          });
        }
      });
    },
  },
};

export default IndexModel;
